package com.example.work3.tools;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.time.Instant;
import java.util.HashMap;
import java.util.Map;

public class Jjwt {
    //用户名和权限（生成token）
    public static String createToken(String account,Integer role){
        Map<String, Object> claims=new HashMap<>();
        claims.put("account",account);
        claims.put("role",role);
        return JWT.create()
                .withClaim("user", claims)//添加载荷
                .withExpiresAt(Instant.ofEpochSecond(System.currentTimeMillis() + 1000 * 60 * 60 * 24))//设置过期时间
                .sign(Algorithm.HMAC256("goudan"));
    }
    //解析token
    public static Map<String, Claim> parseToken(String token){
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256("goudan")).build();
        DecodedJWT decodedJWT = verifier.verify(token);//验证
        Map<String,Claim> claim = decodedJWT.getClaims();
        System.out.println(claim.get("user"));
        return claim;
    }
}
